package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constant.MqConstants;
import com.example.dto.OrderSearchDto;
import com.example.dto.ReturnApplyDto;
import com.example.entity.*;
import com.example.entity.enums.ReturnStatusEnum;
import com.example.event.RefundEvent;
import com.example.event.publisher.EventPublisher;
import com.example.mapper.OrderReturnApplyMapper;
import com.example.param.OrderSearchParams;
import com.example.service.*;
import com.example.vo.LoginUser;
import com.example.vo.Result;
import com.example.vo.ResultCode;
import com.example.vo.UserAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author circle48
* @description 针对表【order_return_apply(订单退货申请)】的数据库操作Service实现
* @createDate 2024-06-09 15:37:34
*/
@Service
public class OrderReturnApplyServiceImpl extends ServiceImpl<OrderReturnApplyMapper, OrderReturnApply>
    implements OrderReturnApplyService{
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private StoreService storeService;


    @Autowired
    private UserAddressService userAddressService;


    @Autowired
    private UserService userService;


    @Autowired
    private EventPublisher eventPublisher;

    @Autowired
    private RefundEvent refundEvent;


    @Override
    public Result<List<ReturnApplyDto>> getReturnList(){
        List<ReturnApplyDto> returnApplys = baseMapper.getReturnList();
        for(ReturnApplyDto returnApplyDto: returnApplys){
            returnApplyDto.convertStatusDesc();
        }
        return Result.ok(returnApplys);
    }

    @Override
    public Result<List<ReturnApplyDto>> searchReturn(OrderSearchDto orderSearchDto){
        List<ReturnApplyDto> returnApplys = baseMapper.searchReturn(orderSearchDto);
        for(ReturnApplyDto returnApplyDto: returnApplys){
            returnApplyDto.convertStatusDesc();
        }
        return Result.ok(returnApplys);
    }

    @Override
    public Result<ReturnApplyDto> getReturnDetail(Long id){
        ReturnApplyDto returnApplyDto = baseMapper.getReturnDetailById(id);
        returnApplyDto.convertStatusDesc();
        return Result.ok(returnApplyDto);
    }
    @Override
    public Result createReturnApply(OrderReturnApply orderReturnApply) {


        Order order = orderService.getById(orderReturnApply.getOrderId());
        // 根据 orderId 和 skuId 获取订单和商品信息
        OrderItem orderItem = orderItemService.getByOrderAndSkuId(orderReturnApply.getOrderId(),orderReturnApply.getSkuId());
        if (orderItem == null) {
            return Result.error("订单不存在");
        }

        // 设置商品相关信息
        orderReturnApply.setSkuImg(orderItem.getSkuPic());
        orderReturnApply.setSkuName(orderItem.getSkuName());
        orderReturnApply.setSkuAttrsVals(orderItem.getSkuAttrsVals());
        orderReturnApply.setSkuCount(orderItem.getSkuQuantity());
        orderReturnApply.setSkuPrice(orderItem.getSkuPrice());
        orderReturnApply.setSkuRealPrice(orderItem.getRealAmount());
        orderReturnApply.setReturnAmount(orderItem.getRealAmount());
        orderReturnApply.setStoreId(order.getStoreId());
        // 获取当前登录会员
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        orderReturnApply.setUserUsername(loginUser.getUser().getNickName());

        if (orderReturnApply.getIsReturn() == 1) {
            // 如果需要退货，设置收货信息
            UserAddressVo address = userAddressService.getDefaultMemberAddress();
            orderReturnApply.setReturnName(address.getName());
            orderReturnApply.setReturnPhone(address.getPhone());

            // 设置公司收货地址
            Store store = storeService.getById(order.getStoreId());
            User u = userService.getById(store.getUserId());
            orderReturnApply.setReceiveMan(u.getNickName());
            orderReturnApply.setCompanyAddress(store.getStoreAddressPath() + store.getStoreAddressDetail());
        } else {
            // 如果仅退款，清空收货信息
            orderReturnApply.setReturnName(null);
            orderReturnApply.setReturnPhone(null);
            orderReturnApply.setReceiveMan(null);
            orderReturnApply.setCompanyAddress(null);
        }
        // 设置申请时间
        orderReturnApply.setCreateTime(LocalDateTime.now());
        orderReturnApply.setStatus(ReturnStatusEnum.TODO);  // 设置申请状态为待处理

        // 插入退货申请记录
        baseMapper.insert(orderReturnApply);
        sendRefundMessage(orderReturnApply);
        return Result.ok("退货申请已提交");
    }

    public void sendRefundMessage(OrderReturnApply refunds) {
        int delayTime = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
        eventPublisher.publish(MqConstants.Exchange.ORDER_EXCHANGE, MqConstants.Key.ORDER_REFUND_KEY, refundEvent.buildEventMessage(refunds), delayTime);
    }
    @Override
    public Result getMyRefundOrders(String username, OrderSearchParams params) {
        LambdaQueryWrapper<OrderReturnApply> queryWrapper = new LambdaQueryWrapper<>();

        // 根据用户名添加查询条件，确保只查询该用户的订单
        queryWrapper.eq(OrderReturnApply::getUserUsername, username);

        // 根据订单状态添加查询条件
        if (params.getRefundStatus() != null && !"ALL".equals(params.getRefundStatus())) {
            try {
                // 将字符串转换为 ReturnStatusEnum 枚举
                ReturnStatusEnum returnStatusEnum = ReturnStatusEnum.valueOf(params.getRefundStatus());

                // 使用枚举的 code 进行查询
                queryWrapper.eq(OrderReturnApply::getStatus, returnStatusEnum.getCode());
            } catch (IllegalArgumentException e) {
                // 如果转换失败，打印错误日志（可选）
                System.err.println("Invalid refund status: " + params.getRefundStatus());
            }
        }

        // 添加按时间排序条件，最新的订单放前面
        queryWrapper.orderByDesc(OrderReturnApply::getCreateTime);

        // 分页查询订单
        Page<OrderReturnApply> page = new Page<>(params.getPageNum(), params.getPageSize());

        // 执行查询
        IPage<OrderReturnApply> resultPage = baseMapper.selectPage(page, queryWrapper);


        // 返回分页查询结果
        return Result.ok(resultPage);
    }

    @Override
    public Result updateReturnApplyDeliverySn(Long id, String deliverySn) {
        LambdaQueryWrapper<OrderReturnApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderReturnApply::getId, id)
                .eq(OrderReturnApply::getIsReturn, 1);

        OrderReturnApply orderReturnApply = baseMapper.selectOne(queryWrapper);

        if (orderReturnApply == null) {
            return Result.error(ResultCode.ORDER_STATUS_WRONG);
        }
        if (orderReturnApply.getStatus() !=ReturnStatusEnum.AGREE) {
            return Result.error(ResultCode.ORDER_STATUS_NOT_ALLOWED);
        }
        orderReturnApply.setDeliverySn(deliverySn);
        orderReturnApply.setStatus(ReturnStatusEnum.RETURNING);

        int updateResult = baseMapper.updateById(orderReturnApply);
        if (updateResult > 0) {
            return Result.ok(ResultCode.UPDATE_LOGISTICS_SUCCESS);
        } else {
            return Result.error(ResultCode.UPDATE_LOGISTICS_FAILED);
        }
    }

    @Override
    public Result<List<ReturnApplyDto>> getReturnListByStoreId(Long storeId){
        List<ReturnApplyDto> returnApplys = baseMapper.getReturnListByStoreId(storeId);
        for(ReturnApplyDto returnApplyDto: returnApplys){
            returnApplyDto.convertStatusDesc();
        }
        return Result.ok(returnApplys);
    }

    @Override
    public Result<List<ReturnApplyDto>> searchReturnByStoreId(Long storeId, OrderSearchDto orderSearchDto){
        List<ReturnApplyDto> returnApplys = baseMapper.searchReturnByStoreId(storeId, orderSearchDto);
        for(ReturnApplyDto returnApplyDto: returnApplys){
            returnApplyDto.convertStatusDesc();
        }
        return Result.ok(returnApplys);
    }

    @Override
    public boolean updateOrderReturn(Long id, String handleNote, Integer status){
        return baseMapper.updateOrderReturn(id,handleNote,status)>0;
    }

}




